package com.DHH.Controller.Identity;

import com.DHH.Dto.*;
import com.DHH.Entity.Base.BaseUser;
import com.DHH.Entity.Capital.CapitalSecurityGivebackRecord;
import com.DHH.Entity.Identity.IdentityAuthenticationState;
import com.DHH.Mapper.Base.BaseUserMapper;
import com.DHH.Mapper.Capital.CapitalSecurityGivebackRecordMapper;
import com.DHH.Mapper.Identity.IdentityAuthenticationMapper;
import com.DHH.Entity.Identity.IdentityAuthentication;
import com.DHH.Mapper.Identity.IdentityAuthenticationStateMapper;
import com.DHH.Service.Identity.IIdentityAuthenticationService;
import com.DHH.Util.ReflectionUtils;
import com.DHH.Util.SMS;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;


/**
 * Created by Administrator on 2017/4/15.
 */
@Controller
@RequestMapping("Admin/Identity/IdentityAuthentication")
public class IdentityAuthenticationController {
    private Logger logger= LoggerFactory.getLogger(IdentityAuthenticationController.class);
    @Autowired
    private IdentityAuthenticationMapper identityAuthenticationMapper;
    @Autowired
    private IIdentityAuthenticationService identityAuthenticationService;
    @Autowired
    private IdentityAuthenticationStateMapper identityAuthenticationStateMapper;
    @Autowired
    private CapitalSecurityGivebackRecordMapper capitalSecurityGivebackRecordMapper;
    @Autowired
    private BaseUserMapper baseUserMapper;

    @RequestMapping("/getIdCount")
    @ResponseBody
    public Message getCount(){
        IdentityAuthentication identityAuthentication=new IdentityAuthentication();
        identityAuthentication.setStateId(1);
        Integer count=identityAuthenticationMapper.selectCount(identityAuthentication);

        CapitalSecurityGivebackRecord capitalSecurityGivebackRecord=new CapitalSecurityGivebackRecord();
        capitalSecurityGivebackRecord.setStateId(1);
        Integer mcount=capitalSecurityGivebackRecordMapper.selectCount(capitalSecurityGivebackRecord);
        Message message=new Message();
        message.setState(true);
        CountData countData=new CountData();
        countData.setIden(count);
        countData.setSecMoney(mcount);
        message.setData(countData);
        return  message;
    }
    @RequestMapping("/listPage")
    public String listPage(HttpSession session,ModelMap modelMap){
        List<IdentityAuthenticationState> identityAuthenticationStateList=identityAuthenticationStateMapper.selectAll();
        modelMap.put("identityAuthenticationStateList",identityAuthenticationStateList);
        return "admin/identityAuthentication/listIdentityAuthenticationPage.jsp";
    }
    @RequestMapping("/addPage")
    public String addPage(HttpSession session,ModelMap modelMap){
            return "admin/identityAuthentication/addIdentityAuthenticationPage.jsp";
    }
    @RequestMapping("/deletePage")
    public String delete(HttpSession session,@RequestParam Integer id,ModelMap modelMap)
    {
        identityAuthenticationMapper.deleteByPrimaryKey(id);
        List<IdentityAuthenticationState> identityAuthenticationStateList=identityAuthenticationStateMapper.selectAll();
        modelMap.put("identityAuthenticationStateList",identityAuthenticationStateList);
        return "admin/identityAuthentication/listIdentityAuthenticationPage.jsp";
    }

    @RequestMapping("/updatePage")
    public String updatePage(HttpSession session,@RequestParam Integer id,ModelMap modelMap)
    {
        IdentityAuthentication identityAuthentication=new IdentityAuthentication();
        identityAuthentication.setId(id);
        identityAuthentication=identityAuthenticationMapper.selectIdentityAuthenticationById(identityAuthentication);
        List<IdentityAuthenticationState> identityAuthenticationStateList=identityAuthenticationStateMapper.selectAll();
        modelMap.put("identityAuthentication",identityAuthentication);
        modelMap.put("identityAuthenticationStateList",identityAuthenticationStateList);
        return "admin/identityAuthentication/updateIdentityAuthenticationPage.jsp";
    }
    @RequestMapping("/detailsPage")
    public String detailPage(HttpSession session,@RequestParam Integer id,ModelMap modelMap)
    {
        return "admin/identityAuthentication/detailsIdentityAuthenticationPage.jsp";
    }

    @RequestMapping("/update")
    @ResponseBody
    public Message update(IdentityAuthentication identityAuthentication)
    {
        Message msg=new Message();
        try{
            identityAuthenticationService.updateIdentityAuthentication(identityAuthentication);
            identityAuthentication=identityAuthenticationMapper.selectIdentityAuthenticationById(identityAuthentication);
            Integer state=identityAuthentication.getStateId();

            BaseUser baseUser=new BaseUser();
            baseUser.setId( identityAuthentication.getUserId());
            baseUser=baseUserMapper.selectByPrimaryKey(baseUser);
            if(state==2){
                SMS.sendIdentityFail(baseUser.getPhone());
            }else{
                if(state==3){
                    SMS.sendIdentityOk(baseUser.getPhone());
                }
            }
            msg.setData(identityAuthentication);
            msg.setMsg("操作成功！");
            msg.setState(true);
            return msg;
        }catch (Exception e)
        {   msg.setMsg("操作失败，请稍后重试");
            return msg;
        }
    }


    @ResponseBody
    @RequestMapping("/query")
    public PageInfo<IdentityAuthentication> query(QueryInfo queryInfo) {
        System.err.println("--------------查询参数---------------");
        System.err.println(queryInfo);
        System.err.println("--------------查询参数---------------");
        /*为查询设置统一分页条件和排序条件*/
        PageHelper.startPage(queryInfo.getCurrentPage(), queryInfo.getPageSize());
        PageHelper.orderBy("create_time desc");
        if(queryInfo.getType()==null)
        {
            queryInfo.setType("search");
        }
        if(queryInfo.getCurrentPage()==null)
        {
            queryInfo.setCurrentPage(1);
        }
        if(queryInfo.getPageSize()==null)
        {
            queryInfo.setPageSize(10);
        }
        try{
            if(queryInfo.getType().equals("screen"))
             {
                   return this.screen(queryInfo);
             }
             if(queryInfo.getType().equals("filter"))
            {

                   return this.searchFilter(queryInfo);
            }
             return this.search(queryInfo);
        }catch (Exception e)
        {
            PageInfo<IdentityAuthentication> p=new PageInfo<IdentityAuthentication>();
            e.printStackTrace();
            p.setMsg("查询失败，请稍后重试！");
            return p;
        }

    }



    /**
     * 查询
     * @param queryInfo
     * @return
     */
    private PageInfo<IdentityAuthentication> search(QueryInfo queryInfo)
    {   System.out.println("---------\n"+queryInfo);

        IdentityAuthentication identityAuthentication=new IdentityAuthentication();
            /*在这里设置相关的查询参数*/
        PageInfo<IdentityAuthentication> pageInfo =new PageInfo<IdentityAuthentication>();
        BaseUser baseUser=new BaseUser();
        baseUser.setIdentity("%"+queryInfo.getSearchKey()+"%");
        identityAuthentication.setBaseUser(baseUser);
        Page<IdentityAuthentication> page = (Page<IdentityAuthentication>) identityAuthenticationMapper.searchByIdentityAuthentication(identityAuthentication);
        pageInfo.setRows(page.getResult());
        pageInfo.setTotalRow(page.getTotal());
        pageInfo.setCurrentPage(queryInfo.getCurrentPage());
       return pageInfo;
    }

    /**
     * 筛选
     * @param queryInfo
     * @return
     */
    private  PageInfo<IdentityAuthentication> screen(QueryInfo queryInfo) {
    	PageInfo<IdentityAuthentication> pageInfo=new PageInfo< IdentityAuthentication>();
    	 IdentityAuthentication identityAuthentication=new  IdentityAuthentication();
        for (String key : queryInfo.getMap().keySet()) {
               ReflectionUtils.setFieldValue(identityAuthentication,key,queryInfo.getMap().get(key));
        }
        Page<IdentityAuthentication> page = (Page<IdentityAuthentication>) identityAuthenticationMapper.screenByIdentityAuthentication(identityAuthentication);
        pageInfo.setRows(page.getResult());
        pageInfo.setTotalRow(page.getTotal());
        pageInfo.setCurrentPage(queryInfo.getCurrentPage());
        return pageInfo;
    }

    /**
     * 过滤
     * @param queryInfo
     * @return
     */
    private PageInfo<IdentityAuthentication> searchFilter(QueryInfo queryInfo) throws ParseException {    IdentityAuthentication identityAuthentication=new  IdentityAuthentication();
    	PageInfo<IdentityAuthentication> pageInfo=new PageInfo< IdentityAuthentication>();
        FilterQuery filterQuery = new FilterQuery();
        filterQuery.setStartValue(queryInfo.getFilterStartValue());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        filterQuery.setEndValue(sdf.format(new Date(sdf.parse(queryInfo.getFilterEndValue()).getTime() + 24 * 3600 * 1000)));
        Page<IdentityAuthentication> page = (Page<IdentityAuthentication>)identityAuthenticationMapper.filterByIdentityAuthentication(filterQuery);
        pageInfo.setRows(page.getResult());
        pageInfo.setTotalRow(page.getTotal());
        pageInfo.setCurrentPage(queryInfo.getCurrentPage());
        return pageInfo;
    }
}

